package com.aaa.config;

import com.aaa.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled = true)
public class MyResourceConfig extends ResourceServerConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
        http.exceptionHandling().accessDeniedHandler((httpServletRequest, httpServletResponse, e) -> {
            Result fail = Result.fail("权限不允许！！！");
            printJsonData(httpServletResponse,fail);
        });
    }


    public void printJsonData(HttpServletResponse httpServletResponse, Result success) throws IOException {
        //

        ObjectMapper objectMapper = new ObjectMapper();
        httpServletResponse.setContentType("application/json;charset=utf8");
        PrintWriter writer = httpServletResponse.getWriter();
        String s = objectMapper.writeValueAsString(success);
        writer.print(s);
        writer.flush();
        writer.close();
    }

    //解析token

    @Bean
    public JwtTokenStore getTokenStore() {
        JwtTokenStore jwtTokenStore = new JwtTokenStore(getConvert());
        return jwtTokenStore;
    }

    /**
     * 解析  生成jwt
     * @return
     */
    @Bean
    public JwtAccessTokenConverter getConvert() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("yyl");// 设置签名的key
        return jwtAccessTokenConverter;
    }
}
